<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin = true" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form
      ref="formCom"
      class="form"
      :validation-schema="thisSchema"
      v-slot="{ errors }"
    >
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              :class="{ error: errors.account }"
              name="account"
              v-model="form.account"
              type="text"
              placeholder="请输入用户名或手机号"
            />
          </div>
          <div class="error" v-if="errors.account">
            <i class="iconfont icon-warning" />{{ errors.account }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field
              v-model="form.password"
              :class="{ error: errors.password }"
              name="password"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          <div class="error" v-if="errors.password">
            <i class="iconfont icon-warning" />{{ errors.password }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              v-model="form.mobile"
              :class="{ error: errors.mobile }"
              name="mobile"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <div class="error" v-if="errors.mobile">
            <i class="iconfont icon-warning" />{{ errors.mobile }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field
              v-model="form.code"
              :class="{ error: errors.code }"
              name="code"
              type="text"
              placeholder="请输入验证码"
            />
            <span class="code" @click="sendMsg" :class="{ disable: time > 0 }">
              {{ time <= 0 ? "发送验证码" : `${time}秒后发送` }}</span
            >
          </div>
          <div class="error" v-if="errors.code">
            <i class="iconfont icon-warning" />{{ errors.code }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <Field as="CheckBox" v-model="form.isAgree" name="isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree">
          <i class="iconfont icon-warning" />{{ errors.isAgree }}
        </div>
      </div>
      <a @click="login" href="javascript:;" class="btn">登录</a>
    </Form>
    <div class="action">
      <!-- 回调网站没了，先不做这块了 -->
      <!-- <img
        src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
        alt=""
      /> -->
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, watch, getCurrentInstance, onMounted } from "vue";
import { Field, Form, validate } from "vee-validate";
import schema from "utils/veeValidateSchema.js";
import Toast from "components/common/toast";
import {
  userAccountLogin,
  userMobileLoginMsg,
  userMobileLogin,
} from "api/user";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import { useIntervalFn } from "@vueuse/core";
export default {
  name: "LoginForm",
  components: {
    Field,
    Form,
  },
  setup() {
    const isMsgLogin = ref(false);
    const form = reactive({
      isAgree: true,
      account: null,
      password: null,
      mobile: null,
      code: null,
    });
    // 校验步骤
    // 1、导入组件，替换，给组件加上name
    // 2、Field数据绑定,名字与字段与后台接口一致
    // 3、定义name属性指定的校验规则函数 :validation-schema接受校验规则，多个规则组合成为对象
    const thisSchema = {
      // 规则，返回true则为成功，返回字符串为失败，字符串为错误提示
      account: schema.account,
      password: schema.password,
      mobile: schema.mobile,
      code: schema.code,
      // 组件有问题，无法点击，换成input等测试无问题，插件版本已更换过
      isAgree: schema.isAgree,
    };
    const formCom = ref(null);
    watch(isMsgLogin, () => {
      // 如果用v-show那这里需要将表单清除，防止以前的校验单纯的隐藏，没有销毁重构
      // 方法1、
      // form.isAgree= true,
      // form.account= null,
      // form.password= null,
      // form.mobile= null,
      // form.code= null,
      // 方法2、
      // 补充校验效果清除，Form组件提供resetForm()
      // 先在外面ref定位Form组件
      // formCom.value.resetForm();
    });

    // Vue3拿到当前实例，不同于vue2的this
    // const { proxy } = getCurrentInstance();
    // 点击登录时，整体表单校验
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const login = async () => {
      // Form整体校验方法：validate，返回一个promise
      const valid = await formCom.value.validate();
      if (valid) {
        let data = null;
        // 整体封装，try成功继续执行，若data捕获catch，直接跑catch
        try {
          if (isMsgLogin.value) {
            // 手机登录
            const { mobile, code } = form;
            data = await userMobileLogin({ mobile, code });
          } else {
            // 帐号登录
            const { account, password } = form;
            data = await userAccountLogin({ account, password });
            // 下列代码封装
            // userAccountLogin({ account, password })
            //   .then((res) => {
            //     console.log(res.result);
            //     //存储信息
            //     const { id, account, nickname, avatar, token, mobile } =
            //       res.result;
            //     store.commit("user/setUser", {
            //       id,
            //       account,
            //       nickname,
            //       avatar,
            //       token,
            //       mobile,
            //     });
            //     //路由跳转回登录前一页
            //     router.push(route.query.redirectUrl || "/");
            //     Toast({ text: "登录成功", type: "success" });
            //   })
            //   .catch((err) => {
            //     if (err.response.data) {
            //       Toast({
            //         text: err.response.data.message || "登录失败",
            //         type: "error",
            //       });
            //     } else {
            //       Toast({ text: "登录失败", type: "error" });
            //     }
            //   });
            // proxy.$Toast("登录成功", "success");
          }
          const { id, account, nickname, avatar, token, mobile } = data.result;
          store.commit("user/setUser", {
            id,
            account,
            nickname,
            avatar,
            token,
            mobile,
          });
          //先合并购物车
          store.dispatch("cart/mergeCart").then(() => {
            // 路由跳转回登录前一页
            router.push(route.query.redirectUrl || "/");
            Toast({ text: "登录成功", type: "success" });
          });
        } catch (e) {
          if (e.response.data) {
            Toast({
              text: e.response.data.message || "登录失败",
              type: "error",
            });
          } else {
            Toast({ text: "登录失败", type: "error" });
          }
        }
      } else {
        Toast({ text: "填写格式无效，请检查", type: "error" });
        // proxy.$Toast("登录失败，请检查用户名或密码", "error");
      }
    };

    // vueuse定时器  useIntervalFn(回调函数，时间，是否立即执行)
    const time = ref(0);
    const { resume, pause } = useIntervalFn(
      () => {
        time.value--;
        if (time.value <= 0) {
          pause();
        }
      },
      1000,
      false
    );
    onMounted(() => {
      pause();
    });
    // 验证码发送
    const sendMsg = async () => {
      // 单表单验证，类似正则test
      const valid = thisSchema.mobile(form.mobile);
      if (valid === true) {
        // 成功
        // 发送验证码
        if (time.value <= 0) {
          // 这里要注册过的手机号才能发送验证码，有点坑，记录一下13666666666
          await userMobileLoginMsg(form.mobile).then((res) => {
            console.log(res);
          });
          Toast({ text: "短信发送成功", type: "success" });
          // 60秒后再次发送：可以用setInterval，也可以用vueUse的功能
          // setInterval
          time.value = 60;
          resume();
          // 验证码校验
        }
      } else {
        // 失败，应该使用vee错误，不用toast
        formCom.value.setFieldError("mobile", valid);
      }
    };
    return { isMsgLogin, form, thisSchema, login, formCom, sendMsg, time };
  },
};
</script>

<style lang="less" scoped>
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
          &.disable {
            cursor: not-allowed;
          }
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
.disable-click {
  cursor: not-allowed;
}
</style>
